package com.niiwoo.civet.trade.service.local.invest;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.activity.stage.dto.request.prize.ActivityPrizeResetStatusReqDTO;
import com.niiwoo.activity.stage.dto.response.prize.UserPrizeResponseDTO;
import com.niiwoo.activity.stage.service.prize.ActivityPrizeDubboService;
import com.niiwoo.civet.trade.dao.entity.InvestAddInterestRateConfig;
import com.niiwoo.civet.trade.dao.entity.ProjectInvestOrder;
import com.niiwoo.civet.trade.dao.entity.ProjectInvestPrize;
import com.niiwoo.civet.trade.dao.mapper.InvestAddInterestRateConfigMapperExt;
import com.niiwoo.civet.trade.dao.mapper.ProjectInvestPrizeMapperExt;
import com.niiwoo.civet.trade.dto.request.AddInterestRateConfigRequestDTO;
import com.niiwoo.civet.trade.dto.response.AddInterestRateConfigResponseDTO;
import com.niiwoo.civet.trade.enums.OrderInvestTypeEnum;
import com.niiwoo.tripod.provider.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * Created by dell on 2017/12/5.
 */
@Service
public class ProjectInvestPrizeService {

	private static final Logger logger = LoggerFactory.getLogger(ProjectInvestPrizeService.class);

	@Autowired
	private ProjectInvestPrizeMapperExt projectInvestPrizeMapperExt;

	@Autowired
	private InvestAddInterestRateConfigMapperExt investAddInterestRateConfigMapperExt;

	@Autowired
	private InvestService investService;
	@Reference(version = "1.0.0")
	private ActivityPrizeDubboService activityPrizeDubboService;

	/**
	 * 获取加息券配置信息
	 * 
	 * @param addInterestRateConfigRequestDTO
	 * @return
	 */
	public AddInterestRateConfigResponseDTO getAddInterestRateConfig(AddInterestRateConfigRequestDTO addInterestRateConfigRequestDTO) {
		AddInterestRateConfigResponseDTO responseDTO = new AddInterestRateConfigResponseDTO();
		InvestAddInterestRateConfig investAddInterestRateConfig = new InvestAddInterestRateConfig();
		investAddInterestRateConfig.setOrgId(addInterestRateConfigRequestDTO.getOrgId());
		investAddInterestRateConfig.setDeadline(addInterestRateConfigRequestDTO.getDeadline());
		investAddInterestRateConfig.setDeadlineUnit(addInterestRateConfigRequestDTO.getDeadlineUnit());
		investAddInterestRateConfig.setRepaymentType(addInterestRateConfigRequestDTO.getRepaymentType());
		investAddInterestRateConfig.setChannelCode(addInterestRateConfigRequestDTO.getChannelCode());
		InvestAddInterestRateConfig addInterestRateConfig = investAddInterestRateConfigMapperExt.getAddInterestRateConfig(investAddInterestRateConfig);
		if (null != addInterestRateConfig) {
			responseDTO.setId(addInterestRateConfig.getId());
			responseDTO.setAddInterestRate(addInterestRateConfig.getAddInterestRate());
		}
		return responseDTO;
	}

	public AddInterestRateConfigResponseDTO getAddInterestRateConfigById(Long id) {
		AddInterestRateConfigResponseDTO responseDTO = new AddInterestRateConfigResponseDTO();
		InvestAddInterestRateConfig addInterestRateConfig = investAddInterestRateConfigMapperExt.selectByPrimaryKey(id);
		if (null != addInterestRateConfig) {
			BeanUtils.copyProperties(addInterestRateConfig, responseDTO);
		}
		return responseDTO;
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void insertSelective(ProjectInvestPrize projectInvestPrize) {
		projectInvestPrizeMapperExt.insertSelective(projectInvestPrize);
	}

	/**
	 * 投资红包批处理
	 */
	public void investPrizeBatchDeal() {
		List<ProjectInvestPrize> list = projectInvestPrizeMapperExt.selectList();
		for (ProjectInvestPrize projectInvestPrize : list) {
			try {
				boolean needReturnPrize = false;// 是否需要退回红包
				if (Byte.valueOf("2").equals(projectInvestPrize.getType())) {
					needReturnPrize = true;
				} else {
					ProjectInvestOrder projectInvestOrderFromMaster = investService.getProjectInvestOrderFromMaster(projectInvestPrize.getInvestOrderId());
					// 投资订单不存在，或者投资订单取消了，则需要退回红包
					if (null == projectInvestOrderFromMaster || Byte.valueOf("2").equals(projectInvestOrderFromMaster.getStatus())) {
						needReturnPrize = true;
					}
				}
				if (needReturnPrize) {
					UserPrizeResponseDTO userPrizeInfo = activityPrizeDubboService.getUserPrizeInfo(projectInvestPrize.getUserId(), projectInvestPrize.getPrizeId());
					if (OrderInvestTypeEnum.INTELLIGENCE.getType().equals(projectInvestPrize.getInvestType())) {
						intelligencePrizeBack(projectInvestPrize, userPrizeInfo);
					}
					// 原始逻辑，不修改
					else {
						logger.info("红包退回定时任务,红包ID{},用户ID{},投资订单ID{},查询的OrderNo{}",
								projectInvestPrize.getPrizeId(),projectInvestPrize.getUserId(),projectInvestPrize.getInvestOrderId(),userPrizeInfo.getOrderNo());
						if (null != userPrizeInfo && String.valueOf(projectInvestPrize.getInvestOrderId()).equals(userPrizeInfo.getOrderNo())) {
							ActivityPrizeResetStatusReqDTO activityPrizeResetStatusReqDTO = new ActivityPrizeResetStatusReqDTO();
							activityPrizeResetStatusReqDTO.setPrizeId(projectInvestPrize.getPrizeId());
							activityPrizeResetStatusReqDTO.setUserId(projectInvestPrize.getUserId());
							activityPrizeResetStatusReqDTO.setInvestOrderId(projectInvestPrize.getInvestOrderId());
							try {
								activityPrizeDubboService.resetPrizeToReturned(activityPrizeResetStatusReqDTO);
							} catch (BizException e) {
								if (!"ACTSTAGE10025".equals(e.getErrorCode())) {
									throw e;
								}
							}
						}
					}
					ProjectInvestPrize updater = new ProjectInvestPrize();
					updater.setId(projectInvestPrize.getId());
					updater.setStatus(Byte.valueOf("2"));
					projectInvestPrizeMapperExt.updateByPrimaryKeySelective(updater);
				}
			} catch (Exception e) {
				logger.error("投资使用红包状态批处理异常, prizeId={}", projectInvestPrize.getPrizeId(), e);
			}
		}
	}

	/**
	 * 智能投红包回退
	 * 
	 * @param projectInvestPrize
	 */
	private void intelligencePrizeBack(ProjectInvestPrize projectInvestPrize, UserPrizeResponseDTO userPrizeInfo) {
		logger.info("智能投发起红包定时退回任务,投资ID{},红包id{},占用情况{}，红包order{}，退回order{}",projectInvestPrize.getInvestOrderId(),projectInvestPrize.getPrizeId(),userPrizeInfo.getIsUsed(),userPrizeInfo.getOrderNo(),projectInvestPrize.getOrderNo());
		// 红包存在，并且处于占用中
		if (null != userPrizeInfo && Byte.valueOf("3").equals(userPrizeInfo.getIsUsed())) {
			// getOrderNo为空说明是子标，母标要进行匹配
			if (Objects.isNull(projectInvestPrize.getOrderNo()) || String.valueOf(projectInvestPrize.getOrderNo()).equals(userPrizeInfo.getOrderNo())) {
				ActivityPrizeResetStatusReqDTO activityPrizeResetStatusReqDTO = new ActivityPrizeResetStatusReqDTO();
				activityPrizeResetStatusReqDTO.setPrizeId(projectInvestPrize.getPrizeId());
				activityPrizeResetStatusReqDTO.setUserId(projectInvestPrize.getUserId());
				activityPrizeResetStatusReqDTO.setInvestOrderId(projectInvestPrize.getInvestOrderId());
				try {
					activityPrizeDubboService.resetPrizeToReturned(activityPrizeResetStatusReqDTO);
				} catch (BizException e) {
					if (!"ACTSTAGE10025".equals(e.getErrorCode())) {
						throw e;
					}
				}
			}
		}
	}
}
